<?php
//通用函数 willson 2014/9/3

//实例化一个模型类
function m($model) {
	$file = MODEL_PATH . "/{$model}.model.php";
	if (file_exists($file)) {
		include_once($file);
		$class = $model."_model";
		$model = new $class;
		return $model;
	} else {
		error("Missing model file");
	}
}

function object2array($obj) {
	$arr = array();
	if (is_object($obj)) {
		foreach ($obj as $k=>$v) {
			$arr[$k] = $v;
		}
		return $arr;
	}
	return $obj;
}

//将一个activeobject对象格式化输出
function ar2object($active_record_obj) {
	if (is_object($active_record_obj)) {
		$obj = new stdClass();
		$attributes = $active_record_obj->attributes();
		foreach ($attributes as $k=>$attr) {
			$obj->$k = $attr;
		}
		return $obj;
	}
	return $active_record_obj;
}

//将一个activeobject对象输出成数组
function ar2array($active_record_obj) {
	if (is_object($active_record_obj)) {
		if (method_exists($active_record_obj, 'to_array')) {
			$arr = $active_record_obj->to_array();
			//将数字也格式化成字符串输出成json
			if (is_array($arr) && count($arr)) {
				foreach ($arr as $k=>$v) {
					if (is_numeric($v)) {
						$arr[$k] = strval($v);
					}
				}
			}
			return $arr;
		}
	}
	return $active_record_obj;
}

//将一个包含有relationship的AR对象的数组输出成数组
function ars2array($active_record_array, $relationships=array()) {
	if (is_array($active_record_array) && count($active_record_array)) {
		$array = array();
		$results = array();
		foreach ($active_record_array as $k=>$obj) {
			if ($relationships) {
				foreach ($relationships as $name) {
					//if (method_exists($obj, $name)) {
					$results[$name] = array_map("ar2array", $obj->$name);
					//}
				}
			}
			$obj = ar2array($obj);
			if ($results) {
				foreach ($results as $k=>$v) {
					$obj[$k] = $v;
				}
			}
			$array[] = $obj;
		}
		return $array;
	} else {
		return $active_record_array;
	}
}

//上传多个文件
function upload_files($mydir, $field, $num=3, $return_array=false) {
	$files = array();
	for($i=1; $i<=$num; $i++) {
		$files[] = upload_one_file($mydir, $field.$i, $return_array);
	}
	return $files;
}

//上传单个文件
function upload_one_file($mydir, $field, $return_array=false) {
	return upload_file_obj($_FILES, $mydir, $field, $return_array);
}

//上传数组形式文件
//20151211 by ajsong 为了兼容数组形式的file, e.g.: name="pic[]"
function upload_file_array($mydir, $field, $return_array=false) {
	if (!isset($_FILES[$field])) return array();
	$file = $_FILES[$field];
	$name = $file['name'];
    $type = $file['type'];
    $tmp_name = $file['tmp_name'];
    $error = $file['error'];
    $size = $file['size'];
	$files = array();
    for($i=0; $i<count($name); $i++) {
		if ($name[$i] != '') {
			$fileObj = array();
			$fileObj[$field] = array();
			$fileObj[$field]['name'] = $name[$i];
			$fileObj[$field]['type'] = $type[$i];
			$fileObj[$field]['tmp_name'] = $tmp_name[$i];
			$fileObj[$field]['error'] = $error[$i];
			$fileObj[$field]['size'] = $size[$i];
			$files[] = upload_file_obj($fileObj, $mydir, $field, $return_array);
		}
    }
    return $files;
}

//上传文件操作
function upload_file_obj($fileObj, $mydir, $field, $return_array=false, $upload_upyun=true) {
	global $upyun_bucketname, $upyun_operator_name, $upyun_operator_pwd, $upyun_domain;
	global $domain;
	include_once(FRAMEWORK_PATH."/class/upload/class.upload.php");
	include_once(FRAMEWORK_PATH."/third/upyun/upyun.class.php");
	//echo $upyun_bucketname . $upyun_operator_name . $upyun_operator_pwd . $upyun_domain;
	//exit;
	$file_array = array('file'=>'', 'width'=>0, 'height'=>0);
	$file = '';
	if (isset($fileObj[$field]) && $fileObj[$field]['size']>0) {
		$dir = UPLOAD_PATH ."/{$mydir}/".date('Y').'/'.date('m').'/'.date('d');
		$upload_dir = ROOT_PATH . $dir;
		if (!is_dir($upload_dir)) makedir($upload_dir);
		$upload = new Upload($fileObj[$field]);
		if ($upload->uploaded) {
			$name = generate_order_sn();
			$upload->file_new_name_body = $name;
			$upload->Process($upload_dir);
			if ($upload->processed) {
				$file = $dir.'/'.$upload->file_dst_name;
				$file_array['width'] = $upload->image_src_x;
				$file_array['height'] = $upload->image_src_y;
				//上传到又拍云 by willson 2015/9/6
				if ($upload_upyun) {
					$local_file = $upload_dir.'/'.$upload->file_dst_name;
					$upyun = new UpYun($upyun_bucketname, $upyun_operator_name, $upyun_operator_pwd);
					try {
						$fh = @fopen($local_file, 'rb');
						$rsp = @$upyun->writeFile($file, $fh, true);   // 上传图片，自动创建目录
						fclose($fh);
						$file = $upyun_domain . $file;
					}
					catch(Exception $e) {
						//$file = $domain . $file;
						//返回不带域名的路径，和以前兼容
						$file = $file;
					}
				}
				$file_array['file'] = $file;
			}
		}
		$upload->Clean();
	} else if (isset($_POST[$field])) {
		//20150629 by ajsong 修复如果不是文件即以POST形式获取
		$file = $_POST[$field];
		$file_array['file'] = $file;
	}
	//print_r($file_array);
	if ($return_array) {
		return $file_array;
	} else {
		return $file_array['file'];
	}
}

//生成订单序列号
function generate_order_sn() {
	return date("ynjGis").rand(10000, 99999);
}

//导出成excel
function export_excel($rs, $fields, $file_name='') {
	$objPHPExcel = new PHPExcel();
	//表格头
	$column = 'A';
	$row_number = 1;
	foreach ($fields as $k => $field) {
		$cell = "{$column}{$row_number}";
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue("{$cell}", $field);
		$objPHPExcel->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getStyle($cell)->applyFromArray(
			array(
				'font' => array (
					'bold' => true
				),
				'alignment' => array(
					'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
				)
			)
		);
		$column ++;
	}
	$row_number = 2; // 1-based index
	foreach ($rs as $k => $order) {
		$column = 'A';
		$objPHPExcel->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
		foreach ($fields as $field=>$name) {
			if (array_key_exists($field, $fields)) {
				$cell = $column . $row_number;
				$objPHPExcel->getActiveSheet()->setCellValue($cell, "{$order->$field}");
				$objPHPExcel->getActiveSheet()->getStyle($cell)->applyFromArray(
					array(
						'alignment' => array(
							'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
							'wrap' => true,
						)
					)
				);
				$column ++;
			}
		}
		$row_number ++;
	}
	// Redirect output to a client’s web browser (Excel2007)
	header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	header('Content-Disposition: attachment;filename="'.$file_name.time().'.xlsx"');
	header('Cache-Control: max-age=0');
	// If you're serving to IE 9, then the following may be needed
	header('Cache-Control: max-age=1');
	// If you're serving to IE over SSL, then the following may be needed
	header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
	header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
	header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
	header ('Pragma: public'); // HTTP/1.0
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
	$objWriter->save('php://output');
	exit;
}

function export_excel_to_file($rs, $fields, $file_name='') {
	$objPHPExcel = new PHPExcel();
	//表格头
	$column = 'A';
	$row_number = 1;
	foreach ($fields as $k => $field) {
		$cell = "{$column}{$row_number}";
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue("{$cell}", $field);
		$objPHPExcel->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getStyle($cell)->applyFromArray(
			array(
				'font' => array (
					'bold' => true
				),
				'alignment' => array(
					'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
				)
			)
		);
		$column ++;
	}
	$row_number = 2; // 1-based index
	foreach ($rs as $k => $order) {
		$column = 'A';
		$objPHPExcel->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
		foreach ($fields as $field=>$name) {
			if (array_key_exists($field, $fields)) {
				$cell = $column . $row_number;
				$objPHPExcel->getActiveSheet()->setCellValue($cell, "{$order->$field}");
				$objPHPExcel->getActiveSheet()->getStyle($cell)->applyFromArray(
					array(
						'alignment' => array(
							'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
							'wrap' => true,
						)
					)
				);
				$column ++;
			}
		}
		$row_number ++;
	}
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
	$file_name = '/uploadfiles/export/'.$file_name.time().'.xlsx';
	$objWriter->save(ROOT_PATH.$file_name);
	return $file_name;
	//exit;
}

//get ip address
function ip() {
	if (isset($_SERVER)) {
		if (isset($_SERVER['REMOTE_ADDR'])) {
			$myip = $_SERVER['REMOTE_ADDR'];
		} else {
			$myip = '0.0.0.0';
		}
	} else {
		$myip = '0.0.0.0';
	}
	return $myip;
}

//循环创建目录
function makedir($absolute_path, $mode = 0777) {
	if (is_dir($absolute_path)) return true;
	$root_path      = ROOT_PATH;
	$relative_path  = str_replace($root_path, '', $absolute_path);
	$each_path      = explode('/', $relative_path);
	$cur_path       = $root_path; // 当前循环处理的路径
	foreach ($each_path as $path) {
		if ($path) {
			$cur_path = $cur_path . '/' . $path;
			if (!is_dir($cur_path)) {
				if (@mkdir($cur_path, $mode)) {
					@fclose(@fopen($cur_path . '/index.htm', 'w'));
				} else {
					return false;
				}
			}
		}
	}
	return true;
}

//截断过长的字符
function cut_str($sourcestr, $cutlength) {
	$returnstr = '';
	$i = 0;
	$n = 0;
	$str_length = strlen($sourcestr); //字符串的字节数
	while (($n<$cutlength) && ($i<=$str_length)) {
		$temp_str = substr($sourcestr, $i, 1);
		$ascnum = Ord($temp_str); //得到字符串中第$i位字符的ascii码
		if ($ascnum>=224) { //如果ASCII位高与224，
			$returnstr = $returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
			$i = $i+3; //实际Byte计为3
			$n++; //字串长度计1
		} else if ($ascnum>=192){ //如果ASCII位高与192，
			$returnstr = $returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
			$i = $i+2; //实际Byte计为2
			$n++; //字串长度计1
		} else if ($ascnum>=65 && $ascnum<=90) { //如果是大写字母，
			$returnstr = $returnstr.substr($sourcestr,$i,1);
			$i=$i+1; //实际的Byte数仍计1个
			$n++; //但考虑整体美观，大写字母计成一个高位字符
		} else { //其他情况下，包括小写字母和半角标点符号，
			$returnstr = $returnstr.substr($sourcestr,$i,1);
			$i = $i+1; //实际的Byte数计1个
			$n = $n+0.5; //小写字母和半角标点等与半个高位字符宽...
		}
	}
	if ($str_length>$cutlength) {
		$returnstr = $returnstr; // "...";超过长度时在尾处加上省略号
	}
	return $returnstr;
}

//获取月份中文名称
function convert_chinese_month($month) {
	$arr = array("一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月");
	return $arr[$month-1];
}

//将时间转换成刚刚、分钟、小时前
function get_time_word($date) {
	$curr = time();
	//$date = strtotime($date);
	$tmp = $curr - $date;
	if ($tmp < 60) {
		$word = '刚刚';
	} else if ($tmp < 3600) {
		$word = floor($tmp/60).'分钟前';
	} else if ($tmp < 86400) {
		$word = floor($tmp/3600).'小时前';
	} else if ($tmp < 259200) {//3天内
		$word = floor($tmp/86400).'天前';
	} else {
		$word = date('n月j日',$date);
	}
	return $word;
}

//将从数据库查出的记录集的时间转换成更简短可读的时间格式，如刚刚、n分钟前
function convert_rs_time($obj, $field) {
	if ($obj && is_array($obj) && $field) {
		foreach ($obj as $k=>$v) {
			if ($v->$field) $obj[$k]->$field = get_time_word($v->$field);
		}
	}
	return $obj;
}

//将从数据库查出的记录集的时间转换成更简短可读的时间格式，如刚刚、n分钟前
function convert_array_time($obj, $field) {
	if ($obj && is_array($obj) && $field) {
		foreach ($obj as $k=>$v) {
			if ($v[$field]) $obj[$k][$field] = get_time_word($v[$field]);
		}
	}
	return $obj;
}

//生成又拍云缩略图url
function get_upyun_thumb_url($url, $size="") {
	//if ($url && $size) {
	if ($url && $size && !is_my_domain($url)) {
		//产品缩略图
		if (strpos($url, "uploadfiles/") !== FALSE) {
			$url = $url . "!" . $size;
		}
	}
	return $url;
}

//是否本站域名
function is_my_domain($url) {
	global $domain;
	$temp_domain = "ejd.miaomiaostudy.com";
	if (strpos($url, $domain) !== FALSE || strpos($url, $temp_domain) !== FALSE) {
		return true;
	} else {
		return false;
	}
}

//将一个对象、数组的URL转换成带域名的URL
//function add_domain($obj, $urls) {
//}

//格式化URL
//by willson 2015/9/6 处理头像等缩略图的问题
function add_domain($url, $is_avatar=false) {
	global $domain;
	if ($url && strpos($url, "http://")===FALSE && strpos($url, "https://")===FALSE) {
		if (substr($url,0,2) == "//") {
			$url = "http:{$url}";
		} else if (substr($url,0,1) == "/") {
			$url = $domain.$url;
		} else {
			$url = $domain."/".$url;
		}
	}
	if ($url && $is_avatar && strpos($url, "/images/")===FALSE && strpos($url, "!logo")===FALSE) {
		$url .= "!logo";
	}
    return $url;
}

//递归一个数组/对象的属性加上域名
function add_domain_deep($obj, $fields=array()) {
	if (is_object($obj) || is_array($obj)) {
		foreach ($obj as $key => $val) {
			if (is_object($val) || is_array($val)) {
				if (is_object($obj)) {
					$obj->$key = add_domain_deep($val, $fields);
				} else if (is_array($obj)) {
					$obj[$key] = add_domain_deep($val, $fields);
				}
			} else {
				if (in_array($key, $fields)) {
					if (is_object($obj)) {
						$obj->$key = add_domain($val, is_avatar($key));
					} else if (is_array($obj)) {
						$obj[$key] = add_domain($val, is_avatar($key));
					}
				}
			}
		}
	} else {
		$obj = add_domain($obj);
	}
	return $obj;
}

//字符串是否包含avatar字样, 且判断是否本地图片(本地需要返回false,否则会按照又拍云规则增加后缀)
function is_avatar($str) {
	global $domain;
	if ($str) {
		if (strpos($str, "avatar")!==FALSE) {
			if (strpos($str, $domain)!==FALSE || (strpos($str, "http://")===FALSE && strpos($str, "https://")===FALSE)) {
				return false;
			} else {
				return true;
			}
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function addslashes_deep_obj($obj) {
	if (is_object($obj) == true) {
		foreach ($obj as $key => $val) {
			if (($val) == true) {
				$obj->$key = addslashes_deep_obj($val);
			} else {
				$obj->$key = addslashes_deep($val);
			}
		}
	} else {
		$obj = addslashes_deep($obj);
	}
	return $obj;
}

//转义
function addslashes_deep($value) {
	if (empty($value)) {
		return $value;
	} else {
		return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
	}
}

//解码经escape编码的字符串
function unescape($str, $charset='utf8') {
	if ($str=='') return '';
	if ($charset=='utf8') {
		$ret = '';
		$len = strlen($str);
		for ($i=0; $i<$len; $i++) {
			if ($str[$i]=='%' && $str[$i+1]=='u') {
				$val = hexdec(substr($str, $i+2, 4));
				if ($val<0x7f)$ret .= chr($val);
				else if ($val<0x800) $ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));
				else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));
				$i += 5;
			} else if ($str[$i]=='%') {
				$ret .= urldecode(substr($str, $i, 3));
				$i += 2;
			} else $ret .= $str[$i];
		}
		return $ret;
	} else {
		$str = rawurldecode($str);
		preg_match_all("/%u.{4}|&#x.{4};|&#d+;|.+/U",$str,$r);
		$ar = $r[0];
		foreach ($ar as $k=>$v) {
			if (function_exists('mb_convert_encoding')) {
				if (substr($v,0,2)=='%u') $ar[$k] = mb_convert_encoding(pack("H4",substr($v,-4)),"GB2312","UCS-2");
				else if (substr($v,0,3)=='&#x') $ar[$k] = mb_convert_encoding(pack("H4",substr($v,3,-1)),"GB2312","UCS-2");
				else if (substr($v,0,2)=='&#') $ar[$k] = mb_convert_encoding(pack("H4",substr($v,2,-1)),"GB2312","UCS-2");
			}else{
				if (substr($v,0,2)=='%u') $ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,-4)));
				else if (substr($v,0,3)=='&#x') $ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,3,-1)));
				else if (substr($v,0,2)=='&#') $ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,2,-1)));
			}
		}
		return join('', $ar);
	}
}

//生成密码盐值salt
function generate_salt() {
	$salt = rand(100000, 999999);
	return $salt;
}

//根据盐值生成加密密码
function crypt_password($password, $salt) {
	return md5(md5($password).$salt);
}

//生成随机字母、数字
function random_str($length=4) {
	//生成一个包含 大写英文字母, 小写英文字母, 数字 的数组
	$arr = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
	$str = '';
	$arr_len = count($arr);
	for ($i = 0; $i < $length; $i++) {
		$rand = mt_rand(0, $arr_len-1);
		$str .= $arr[$rand];
	}
	return $str;
}

//发送短信
//send_sms("18027196538", rand(1000,9999));
function send_sms($mobile, $content, $template_id=128241) {
	//include_once (FRAMEWORK_PATH."/third/sms/sendsms.class.php");
	//$sms = new sendsms();
	//$str = $sms->send($mobile, $content);
	//return $str;
	include_once (FRAMEWORK_PATH."/third/sms/yuntongxun/CCPRestSmsSDK.php");
	global $sms_accountSid, $sms_accountToken, $sms_appId;
	//沙盒环境（用于应用开发调试）：sandboxapp.cloopen.com
	//生产环境（用户应用上线使用）：app.cloopen.com
	$serverIP = 'sandboxapp.cloopen.com';
	//请求端口，生产环境和沙盒环境一致
	$serverPort = '8883';
	//REST版本号，在官网文档REST介绍中获得。
	$softVersion='2013-12-26';
	$rest = new REST($serverIP, $serverPort, $softVersion);
	$rest->setAccount($sms_accountSid, $sms_accountToken);
	$rest->setAppId($sms_appId);
	//发送模板短信
	if (is_array($content)) {
		$result = $rest->sendTemplateSMS($mobile, $content, $template_id);
	} else {
		if (trim($content)=='') {
			$result = $rest->sendTemplateSMS($mobile, array(), $template_id);
		} else {
			$result = $rest->sendTemplateSMS($mobile, array($content), $template_id);
		}
	}
	if ($result == NULL ) {
		return;
		//echo "result error!";
		//break;
	}
	if ($result->statusCode!=0) {
		//echo "error code :" . $result->statusCode . "<br>";
		//echo "error msg :" . $result->statusMsg . "<br>";
		//TODO 添加错误处理逻辑
	} else {
		//echo "Sendind TemplateSMS success!<br/>";
		// 获取返回信息
		//$smsmessage = $result->TemplateSMS;
		//echo "dateCreated:".$smsmessage->dateCreated."<br/>";
		//echo "smsMessageSid:".$smsmessage->smsMessageSid."<br/>";
		//TODO 添加成功处理逻辑
	}
}

//定时发送
/*
$time = '2010-05-27 12:11';
$res = sendSMS($uid, $pwd, $mobile, $content, $time);
echo $res;
*/
/*
短信接口改变了
*/
/*
function send_sms($mobile, $content) {
	global $yun_sms_uid, $yun_sms_password, $yun_sms_sign;
	$uid = $yun_sms_uid;
	$pwd = strtolower(md5($yun_sms_password));
	$content = urlencode($content.$yun_sms_sign);
	$re = file_get_contents("http://http.yunsms.cn/tx/?uid={$uid}&pwd={$pwd}&encode=utf8&mobile={$mobile}&content={$content}");
	if (trim($re) == '100') {
		//echo "ok";
		return 1;
	} else {
		//echo "fail:{$re}";
		return 0;
	}
}
*/

//send_sms("13580405060", time()."您的密码");
/*
function send_sms($mobile, $content) {
	global $yun_sms_uid, $yun_sms_id, $yun_sms_password, $yun_sms_sign;
	$uid = $yun_sms_uid;
	$id = $yun_sms_id;
	$pwd = $yun_sms_password;
	$content = urlencode($content.$yun_sms_sign);
	$re = file_get_contents("http://106.3.37.111:8888/sms.aspx?action=send&userid={$id}&account={$uid}&password={$pwd}&mobile={$mobile}&content={$content}&sendTime=&extno=");
	if (stripos($re, "Success")!==false) {
		//die("ok");
		return 1;
	} else {
		//die("fail:{$re}");
		return 0;
	}
}
*/

//写log文件
function write_log($word='', $filepath="temp/log.txt") {
	$fp = fopen($filepath, "a");
	flock($fp, LOCK_EX) ;
	fwrite($fp, "".strftime("%Y-%m-%d %H:%M:%S",time()).": ".$word."\n");
	flock($fp, LOCK_UN);
	fclose($fp);
}

//防止 json_encode 后中文被转码
function json_encode_urlencode($obj){
	if(!isset($obj))return '';
	$str = '';
	if ( version_compare(PHP_VERSION, '5.4.0', '>=') ) {
		$str = json_encode($str, JSON_UNESCAPED_UNICODE);
	} else {
		$str = urldecode(json_encode(url_encode($obj)));
	}
	return $str;
	//return str_replace(":null", ":\"\"", $str);
}

//将对象/数组进行urlencode
function url_encode($obj){
	$o = deep_clone($obj);
	if(is_array($o)){
		foreach($o as $key=>$value)$o[urlencode($key)] = url_encode($value);
	}else if(is_object($o)){
		foreach($o as $name=>$value)$o->$name = url_encode($o->$name);
	}else if(is_string($o)){
		$o = urlencode($o);
	}
	return $o;
}

//深度复制(防止PHP直接赋值到新变量后仍然指向同一内存指针)
function deep_clone($obj){
	$o = '';
	if(is_array($obj)){
		$o = array();
		foreach($obj as $key=>$value)$o[$key] = unserialize(serialize($value));
	}else if(is_object($obj)){
		$o = new stdClass();
		foreach($obj as $name=>$value)$o->$name = unserialize(serialize($obj->$name));
	}else{
		$o = unserialize(serialize($obj));
	}
	return $o;
}

function debug($obj){
	echo '<pre>';
	print_r($obj);
	echo '</pre>';
	exit;
}

//格式化价格
function format_price($price) {
	if (is_numeric($price)) {
		$price = number_format($price, 2);
	}
	return $price;
}

//输出script
function script($js) {
	$html = "<meta charset=\"UTF-8\"><script>{$js}</script>";
	exit($html);
}

//判断是否PJAX请求
function isPjax() {
	return array_key_exists('HTTP_X_PJAX', $_SERVER) && $_SERVER['HTTP_X_PJAX'];
}

//POST方式提交数据
function postData($url, $params=array(), $isJson=false){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_POST, TRUE);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
	if (!empty($params)) {
		curl_setopt($ch, CURLOPT_POSTFIELDS, $params); //如果params为数组即使用multipart/form-data提交, 为字符串即使用application/x-www-form-urlencoded
	}
	curl_setopt($ch, CURLOPT_URL, $url);
	if (substr($url, 0, 8)=='https://') {
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //对认证证书来源的检查
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //从证书中检查SSL加密算法是否存在
	}
	$data = curl_exec($ch);
	if ($data === false) {
		echo 'Curl error: ' . curl_error($ch);
		exit;
	}
	curl_close($ch);
	if ($isJson) {
		$data = json_decode($data, true);
		if (is_null($data)) $data = '';
	}
	return $data;
}

//快递鸟 - 物流公司对应字母
//http://www.kdniao.com/YundanChaxunAPI.aspx
function kdniao() {
	return array(
		'EMS' => 'EMS快递',
		'SF' => '顺丰快递',
		'STO' => '申通快递',
		'YTO' => '圆通快递',
		'YD' => '韵达快递',
		'HTKY' => '汇通快递',
		'HHTT' => '天天快递',
		'ZTO' => '中通快递',
		'ZJS' => '宅急送快递',
		'YZPY' => '中国邮政',
		'QFKD' => '全峰快递',
		'GTO' => '国通快递',
		'FAST' => '快捷快递',
		'JD' => '京东快递',
		'LB' => '龙邦快递',
		'DBL' => '德邦物流',
		'RFD' => '如风达快递',
		'QRT' => '全日通快递',
		'JJKY' => '佳吉快运',
		'DHL' => 'DHL快递'
	);
}
function getkdniao($spellName, $mailNo) {
	if (!$spellName || !$mailNo) error('缺少快递单号或订单编号');
	$index = false;
	$kd = kdniao();
	preg_match("/[\x{4e00}-\x{9fa5}]+/u", $spellName, $matches);
	if (count($matches)) {
		$companyName = str_replace('快递','',str_replace('物流','',str_replace('快运','',str_replace('速递','',str_replace('速运','',$spellName)))));
		foreach ($kd as $k => $v) {
			if (strpos($v, $companyName)!==false) {
				$index = $k;
				break;
			}
		}
	} else if (isset($kd[$spellName])) {
		$index = $spellName;
	}
	if ($index === false) error("没有该物流公司代号: {$spellName}");
	$EBusinessID = "1256920"; //电商ID
	$AppKey = "e7bbede8-6d12-439f-9ebf-d835613b638f"; //电商加密私钥
	$requestData = "{\"OrderCode\":\"\", \"ShipperCode\":\"{$index}\", \"LogisticCode\":\"{$mailNo}\"}";
	$dataSign = "{$requestData}{$AppKey}";
	$dataSign = urlencode(base64_encode(md5($dataSign)));
	$postData = array(
		'EBusinessID' => $EBusinessID,
		'RequestType' => '1002',
		'RequestData' => urlencode($requestData),
		'DataType' => '2',
		'DataSign' => $dataSign
	);
	$json = postData('http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx', $postData, true, true);
	if (is_array($json)) {
		if (intval($json['Success'])==1) {
			//$json['State'] 2:在途中, 3:签收, 4:问题件
			$result = json_encode($json);
			$result = str_replace('"AcceptStation":', '"context":', $result);
			$result = str_replace('"AcceptTime":', '"time":', $result);
			$result = str_replace('"Traces":', '"data":', $result);
			$json = json_decode($result, true);
			if (!is_null($json) && is_array($json['data'])) {
				return $json;
			} else {
				return getickd($spellName, $mailNo);
			}
		} else {
			error($json['Reason']);
		}
	} else {
		error('快递鸟接口发生异常');
	}
}

//爱查快递
//http://www.ickd.cn
function ickd(){
	return array(
		'ems' => 'EMS快递',
		'shunfeng' => '顺丰快递',
		'shentong' => '申通快递',
		'yuantong' => '圆通快递',
		'yunda' => '韵达快递',
		'huitong' => '汇通快递',
		'tiantian' => '天天快递',
		'zhongtong' => '中通快递',
		'zhaijisong' => '宅急送快递',
		'pingyou' => '中国邮政',
		'quanfeng' => '全峰快递',
		'guotong' => '国通快递',
		'kuaijie' => '快捷快递',
		'jingdong' => '京东快递',
		'ririshun' => '日日顺物流',
		'longbang' => '龙邦快递',
		'debang' => '德邦物流',
		'rufeng' => '如风达快递',
		'quanritong' => '全日通快递',
		'jiaji' => '佳吉快运',
		'dhl' => 'DHL快递'
	);
}
function getickd($spellName, $mailNo) {
	if (!$spellName || !$mailNo) error('缺少快递单号或订单编号');
	$index = false;
	$kd = ickd();
	preg_match("/[\x{4e00}-\x{9fa5}]+/u", $spellName, $matches);
	if (count($matches)) {
		$companyName = str_replace('快递','',str_replace('物流','',str_replace('快运','',str_replace('速递','',str_replace('速运','',$spellName)))));
		foreach ($kd as $k => $v) {
			if (strpos($v, $companyName)!==false) {
				$index = $k;
				break;
			}
		}
	} else if (isset($kd[$spellName])) {
		$index = $spellName;
	}
	if ($index === false) error("没有该物流公司代号: {$spellName}");
	$data = file_get_contents("http://biz.trace.ickd.cn/{$index}/{$mailNo}?callback=callback");
	if (strpos($data, '/**/callback&&callback(')!==false) {
		$result = str_replace('/**/callback&&callback(', '', $data);
		$result = preg_replace("/<span[^>]+?>/", '', $result);
		$result = str_replace('<\\/span>', '', $result);
		$result = substr($result, 0, strlen($result)-1);
		$json = json_decode($result, true);
		if (!is_null($json)) {
			if (intval($json['errCode'])==0) {
				if (is_array($json['data'])) {
					return $json;
				} else {
					return getkd100($spellName, $mailNo);
				}
			} else {
				error($json['message']);
			}
		} else {
			exit($data);
		}
	} else {
		error('爱查快递接口发生异常');
	}
}

//快递100
//http://www.kuaidi100.com
function kd100(){
	return array(
		'ems' => 'EMS快递',
		'shunfeng' => '顺丰快递',
		'shentong' => '申通快递',
		'yuantong' => '圆通快递',
		'yunda' => '韵达快递',
		'huitongkuaidi' => '汇通快递',
		'tiantian' => '天天快递',
		'zhongtong' => '中通快递',
		'zhaijisong' => '宅急送快递',
		'youzhengguonei' => '中国邮政',
		'quanfengkuaidi' => '全峰快递',
		'guotongkuaidi' => '国通快递',
		'longbanwuliu' => '龙邦快递',
		'debangwuliu' => '德邦物流',
		'rufengda' => '如风达快递',
		'quanritongkuaidi' => '全日通快递',
		'jiajiwuliu' => '佳吉快运',
		'dhl' => 'DHL快递'
	);
}
function getkd100($spellName, $mailNo) {
	if (!$spellName || !$mailNo) error('缺少快递单号或订单编号');
	$index = false;
	$kd = kd100();
	preg_match("/[\x{4e00}-\x{9fa5}]+/u", $spellName, $matches);
	if (count($matches)) {
		$companyName = str_replace('快递','',str_replace('物流','',str_replace('快运','',str_replace('速递','',str_replace('速运','',$spellName)))));
		foreach ($kd as $k => $v) {
			if (strpos($v, $companyName)!==false) {
				$index = $k;
				break;
			}
		}
	} else if (isset($kd[$spellName])) {
		$index = $spellName;
	}
	if ($index === false) error("没有该物流公司代号: {$spellName}");
	$result = file_get_contents("http://www.kuaidi100.com/query?type={$index}&postid={$mailNo}");
	$json = json_decode($result, true);
	if (is_array($json)) {
		if (intval($json['status'])==200 && is_array($json['data'])) {
			return $json['data'];
		} else {
			error($json['message']);
		}
	} else {
		error('快递100接口发生异常');
	}
}

//获取表单数据 by @jsong 2016-6-26
//兼容普通提交、RSA提交
function getDatas() {
	global $table_prefix;
	if (RSA_POST && strtoupper($_SERVER['REQUEST_METHOD'])=='POST') {
		$data = file_get_contents("php://input");
		if (strlen($data)) {
			$_POST = array();
			if (strlen($data)>=684 && strpos($data, '&')===false && substr($data, strlen($data)-1)=='=') {
				$GLOBALS['isRSA'] = true;
				$rsa = new Rsa(FRAMEWORK_PATH . '/class/rsa/keys', "{$table_prefix}private", "{$table_prefix}public");
				$data = $rsa->privDecode($data);
			}
			$json = json_decode($data);
			if (is_null($json)) {
				$arr = explode('&', $data);
				foreach ($arr as $g) {
					$gs = explode('=', $g);
					if (count($gs)>1) $_POST[$gs[0]] = $gs[1];
				}
			} else {
				foreach ($json as $key => $val) $_POST[$key] = $val;
			}
		}
	}
	return $_POST;
}
